package mce.cuce;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class PostgreDb implements Db{

	private String dbName = "test";
	private String username = "postgres";
	private String password = "test";
	private String tableName = "urls";
	private Connection connection;
	private boolean connected;
	
	public PostgreDb() {
		
	}
	
	public void insert(String shortUrl, String longUrl) {
		String sql = "INSERT INTO " + tableName + "(longUrl, shortUrl) VALUES(?, ?)";
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setString(1, longUrl);
			ps.setString(2, shortUrl);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	public String get(String shortUrl) {
		String sql = "SELECT longUrl FROM " + tableName + " WHERE shortUrl=?";
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setString(1, shortUrl);
			ResultSet rs = ps.executeQuery();
			rs.next();
			String longUrl = rs.getNString("longUrl");
			return longUrl;
		} catch (SQLException e) {
			
		}
		return null;
	}

	public int getNextId() {
		String sql = "SELECT id FROM " + tableName + " ORDER BY id DESC LIMIT 1";
		try {
			Statement st = connection.createStatement();
			ResultSet set = st.executeQuery(sql);
			set.next();
			int id = set.findColumn("id");
			return id;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public void delete(int id) {
		String sql = "DELETE FROM " + tableName + " WHERE id=?";
		try {
			PreparedStatement ps = connection.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void setDatabaseName(String name) {
		dbName = name;
	}

	public void setUsername(String name) {
		username = name;
	}
	
	public void setPassword(String pass) {
		password = pass;
	}

	public void connect() {
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		String url = "jdbc:postgresql://localhost/" + dbName;
		Properties props = new Properties();
		props.setProperty("user", username);
		props.setProperty("password", password);
		
		
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, props);
			connection = conn;
			setConnected(true);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void setConnected(boolean connected) {
		this.connected = connected;
	}

	public boolean isConnected() {
		return connected;
	}
}
